package com.dingreading.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/***
 * sentinel限流
 */
@Configuration
public class GatewayConfig {

    @PostConstruct
    public void init() {

        BlockRequestHandler blockRequestHandler = (exchange, t) -> {

            HashMap<String, Object> map = new HashMap<>();
            map.put("st", 500);
            map.put("msg", "访问次数过多，请稍后再试");

            // 自定义异常处理
            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(map));
        };

        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

}
